/**
 * Copyright (c) 2018, dreamkaylee@foxmail.com All Rights Reserved.
 */

package com.common.web;

import java.awt.image.BufferedImage;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;

/**
 * 验证码
 * @author limk
 * @date 2018年2月12日 下午9:15:37
 * @version 1.0
 */
@Component
@RequestMapping("/")
public class KaptchaController {

	private static final Logger logger = LogManager.getLogger(KaptchaController.class);
	
	@Autowired
	private Producer captchaProducer;

	@RequestMapping("/captcha-image")
	public ModelAndView kaptchaImage(HttpServletRequest request, HttpServletResponse response) throws Exception {

		response.setDateHeader("Expires", 0);
		// 设置请求不缓存
		response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
		response.addHeader("Cache-Control", "post-check=0, pre-check=0");
		response.setHeader("Pragma", "no-cache");
		// 返回的图片格式
		response.setContentType("image/jpeg");
		// 图片里显示的文字
		String capText = captchaProducer.createText();
		// 放入session
		request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
		logger.info(request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY));
		// 创建图片
		BufferedImage bi = captchaProducer.createImage(capText);
		ServletOutputStream out = response.getOutputStream();
		// 回写
		ImageIO.write(bi, "jpg", out);
		try {
			out.flush();
		} finally {
			out.close();
		}
		return null;
	}

}
